package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 菜单管理 控制层
 */
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MenuService menuService;

    /**
     * 分页查询
     * @param queryPageBean 分页查询的条件
     * @return 返回当前页的所有菜单数据
     */
    @RequestMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
        try {
            PageResult pageResult = menuService.findPage(queryPageBean);
            return new Result(true, MessageConstant.GET_MENU_SUCCESS, pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MENU_FAIL);
        }
    }

    /**
     * 添加菜单
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Menu menu) {
        try {
            boolean isSuccess = menuService.add(menu);
            if (isSuccess) {
                //jedisPool.getResource().sadd(RedisConstant.MENU_PIC_DB_RESOURCES, menu.getIcon());
                return new Result(true, MessageConstant.ADD_MENU_SUCCESS);
            } else {
                return new Result(false, MessageConstant.ADD_MENU_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MENU_FAIL);
        }
    }

    /**
     * 根据 id 查询菜单
     * @param id 菜单id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Menu menu = menuService.findById(id);
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS, menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }

    /**
     * 根据 id 删除菜单
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            boolean isSuccess = menuService.delete(id);
            if (isSuccess) {
                return new Result(true, MessageConstant.DELETE_MENU_SUCCESS);
            } else {
                return new Result(false, MessageConstant.DELETE_MENU_FAIL);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_MENU_FAIL);
        }
    }

    /**
     * 上传图标
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        try {
            //1.将原始文件名改为一个唯一的文件名（保证文件不会被覆盖）
            String originalFilename = imgFile.getOriginalFilename();
            int index = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffx = originalFilename.substring(index);
            //UUID方式生成一个唯一文件名
            String newFileName = UUID.randomUUID().toString() + suffx;//UUID+.jpg
            //2.将图片上传七牛云
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), newFileName);
            //第一步写入redis  key(常量类定义)setmealPicResources value（集合）
            jedisPool.getResource().sadd(RedisConstant.MENU_PIC_RESOURCES, newFileName);
            //3.页面还需要回显图片
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    /**
     * 编辑菜单
     * @param menu
     * @return
     */
    @RequestMapping("/edit")
    public Result edit(@RequestBody Menu menu) {
        try {
            boolean isSuccess = menuService.edit(menu);
            if (isSuccess) {
                return new Result(true, MessageConstant.EDIT_MENU_SUCCESS);
            } else {
                return new Result(false, MessageConstant.EDIT_MENU_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MENU_FAIL);
        }
    }

    /**
     * 查询所有菜单数据
     */
    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            List<Menu> menuList = menuService.findAll();
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS, menuList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }

    /**
     * 根据角色id获取该角色关联的所有菜单项id
     */
    @RequestMapping("/findByRoleId")
    public Result findByRoleId(Integer roleId) {
        try {
            List<Integer> menuIds = menuService.findByRoleId(roleId);
            return new Result(true, MessageConstant.QUERY_MENU_SUCCESS, menuIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MENU_FAIL);
        }
    }

    //动态菜单展示
    @RequestMapping(value = "/findMenu")
    public Result findMenu(String username){
        try {
            final List<Map<String, Object>> menuByUserName = menuService.findMenuByUserName(username);
            return new Result(true,MessageConstant.QUERY_MENU_SUCCESS,menuByUserName);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_MENU_FAIL);
        }
    }
}